package com.heima.gateway.filter;

import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
//@Order(1)
public class AuthorizeFilter implements GlobalFilter, Ordered {

    /**
     * 全局过滤器的过滤方法 ----- 校验token是否合法
     *
     * 校验token是否合法
     *  校验token -  获取token  ---> 请求响应
     *
     *
     * @param exchange 交换机 : 网关和web环境的交换机
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2. 放行登录请求
        String path = request.getURI().getPath();
        if (StringUtils.contains(path, "/login/in")) {
            return chain.filter(exchange);
        }

        //3. 获取请求头中的token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //4. 校验token
        Claims claims = AppJwtUtil.getClaimsBody(token);

        //5. 校验通过放行, 校验失败 返回401
        int result = AppJwtUtil.verifyToken(claims);
        //校验通过, 放行
        if (result == 0 || result == -1) {

            //5.1 获取token中的用户ID
            String userId = claims.get("id").toString();
            //5.2 将userId携带到微服务(放入到请求中)
            ServerHttpRequest httpRequest = request.mutate().headers(httpHeaders -> httpHeaders.add("userId", userId)).build();

            ServerWebExchange webExchange = exchange.mutate().request(httpRequest).build();

            return chain.filter(webExchange);
        }
        //校验失败, 返回401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
